from abc import ABC, abstractmethod
from tools.myjwt import mjwt
from users.models import UserModel, SFUserModel
import requests,time,json

class SFlogin(ABC):

    @abstractmethod
    def geturl(self) -> None:
        pass


    @abstractmethod
    def callback(self,code) -> None:
        pass



class Dingding(SFlogin):
    def __init__(self):
        self.redirect_uri = "http://localhost:5173/dingtalkcallback/"
        self.client_id = "dingeupx9kgcuppqe00m"
        self.clientSecret = "O6ElxmgMlnCDokZwx4mE4CSR41UBnXiKhgyUY06hfao1ZjnaLMyX29BPrfgn9AUO"


    def geturl(self):
            from urllib.parse import quote
            params = [
                f"redirect_uri={quote(self.redirect_uri)}",
                "response_type=code",
                f"client_id={self.client_id}",
                "scope=openid",
                "prompt=consent"
            ]
            url = "https://login.dingtalk.com/oauth2/auth?" + "&".join(params)
            return url

    def  callback(self, code):

            data = {
                "clientId": "dingeupx9kgcuppqe00m",
                "clientSecret": "O6ElxmgMlnCDokZwx4mE4CSR41UBnXiKhgyUY06hfao1ZjnaLMyX29BPrfgn9AUO",
                "code": code,
                "grantType": "authorization_code"
            }
            resp = requests.post('https://api.dingtalk.com/v1.0/oauth2/userAccessToken', json=data).json()
            accessToken = resp.get('accessToken')
            print("accessToken: ", accessToken)

            # 根据accessToken获取用户信息
            headers = {"x-acs-dingtalk-access-token": accessToken}
            resp = requests.get('https://api.dingtalk.com/v1.0/contact/users/me', headers=headers).json()

            name = resp.get('nick')
            uid = resp.get('openId')
            phone = resp.get('mobile')
            print("name: ", name, "uid: ", uid, "phone: ", phone)

            sfl = SFUserModel.objects.filter(uid=uid, type=0).first()
            if not sfl:
                user = UserModel.objects.filter(phone=phone).first()
                if not user:
                    user = UserModel.objects.create(username=name, phone=phone)
                    sfl = SFUserModel.objects.create(user=user, uid=uid, type=0)
                else:
                    sfl = SFUserModel.objects.create(user=user, uid=uid, type=0)
            user = sfl.user

            payload = {
                'user_id': user.id,
                'username': user.username,
                'exp': int(time.time()) + 3600 * 2
            }
            access_token = mjwt.jwt_encode(payload)
            payload['exp'] = int(time.time()) + 3600 * 24 * 3
            refresh_token = mjwt.jwt_encode(payload)
            return {'accessToken': access_token, 'refreshToken': refresh_token,'code':200,'user_id':user.id}


def singleton(cls):
    instances = {}

    def wrapper(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    return wrapper






@singleton
class Factory():
    def create_sflogin(self, type):
        if type == '0':
            return Dingding()
        else:
            raise Exception("暂不支持该登录方式")



factory = Factory()











